import type { AsyncData, UseFetchOptions } from "#app";
// 这两个类型都是nuxt自带的  仔细看看ts封装的方式

const BASE_URL = "http://codercba.com:9060/juanpi/api/";
type Methods = "GET" | "POST";

export interface ResultData<T> {
    code: number;
    data: T;
}

class Request {
    request<T = any> (url:string , method:Methods , data?:any , options? :UseFetchOptions<T>) : Promise<AsyncData<T,Error>> {
        return new Promise((reslove , reject) => {
            // 重新整理一次参数
            const newOptions:UseFetchOptions<T> = {
                baseURL:BASE_URL,
                method,
                ...options,
            }
            // 对 get  post 请求的参数进行分类
            switch (method) {
                case 'GET':
                    newOptions.query = data
                    break;
            
                case 'POST':
                    newOptions.body = data
                    break;
            }

            // 发送请求  使用useFetch 这个api
            useFetch<T>(url , newOptions as any).then((res)=>{
                reslove(res as AsyncData<T,Error>)
            })
            .catch((err)=>{
                reject(err)
            })
        })
    }

    // 封装get请求
    get<T = any>(url:string , params?:any , options?:UseFetchOptions<T> ){
        return this.request(url , 'GET' , params , options)
    }

    // 封装post请求
    post<T = any>(url:string , data?:any , options?:UseFetchOptions<T>){
        return this.request(url , 'POST' , data , options)
    }
}


export default new Request()